//
//  CarServiceTableViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/4.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "CarServiceTableViewController.h"
#import "CarServiceDetailViewController.h"
#import "RegionSeletedViewController.h"
static NSString *cell = @"DrawTrailer";

@interface CarServiceTableViewController (){
   BOOL regionSelete;

}

@end

@implementation CarServiceTableViewController

- (id)init:(NSString *)dicType andIsSendMessegeIsCategory:(BOOL) bol{
    self = [super init];
    if (self) {
        self.dic_type = dicType;
        self.isCarCategory = bol;
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.view.window hideToastActivity];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    regionSelete = NO;
    self.tableView.hidden = YES;
     _currenPage = 1;
    [self initAbout];
    [self initWithData];
}

- (void)netRequest:(CLLocationCoordinate2D )location andRresh:(BOOL)bol{
    if (!self.carAround) {
        self.carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    self.carAround.lat = [NSString stringWithFormat:@"%f",_location.latitude];
    self.carAround.lon = [NSString stringWithFormat:@"%f",_location.longitude];
    self.carAround.dic_type = self.dic_type;
    self.carAround.page = [NSString stringWithFormat:@"%ld",_currenPage];
    [self.carAround carAroundInfo:^(id result) {
        _tableDataSource = [NSMutableArray arrayWithArray:[result objectForKey:@"sellerlist"]];
        _countPage = [[result objectForKey:@"totalpages"] integerValue];
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }anfFail:^(id result) {
        _currenPage --;
        [self.tableView footerEndRefreshing];
    }];
}

- (void)footerRresh {
    if (_countPage <= _currenPage) {
        [self.view.window makeToast:@"没有更多数据了哦"];
        [self.tableView footerEndRefreshing];
        return;
    }
    _currenPage ++;
    self.carAround.lat = [NSString stringWithFormat:@"%f",_location.latitude];
    self.carAround.lon = [NSString stringWithFormat:@"%f",_location.longitude];
    self.carAround.dic_type = self.dic_type;
    self.carAround.page = [NSString stringWithFormat:@"%ld",_currenPage];
    [self.carAround carAroundInfo:^(id result) {
        [_tableDataSource addObjectsFromArray:[result objectForKey:@"sellerlist"]];
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    }anfFail:^(id result) {
        _currenPage --;
        [self.tableView footerEndRefreshing];
    }];
    
}


- (void)regionSeleteAction:(NSDictionary *)info {
    _currenPage = 1;
    _countPage = 0;
    [_rightBtn setTitle:[info customObjectForkey:@"city"] forState:UIControlStateNormal];
    _location.latitude = [[info customObjectForkey:@"LAT"] floatValue];
    _location.longitude = [[info customObjectForkey:@"LON"] floatValue];
    [self netRequest:_location andRresh:NO];
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, [RextExtends getScreenFrame].size.width, [RextExtends getScreenFrame].size.height) animated:YES];

}


- (void)viewDidDisappear:(BOOL)animated{
    _search.delegate = nil;
}

- (void)viewWillAppear:(BOOL)animated{
    if (_search) {
        _search.delegate = self;
    }
}

- (void)initWithData{
    if ([Common currenCity] && [[Common currenCity] customObjectForkey:@"location"]) {
        _location.latitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lat"] doubleValue];
        _location.longitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lon"] doubleValue];
        if([self.dic_type isEqualToString:@"meishi"]){
            [self baiduMeishiSearch];
        }else{
            [self netRequest:_location andRresh:NO];
        }
        [self setRightBtnTitle];
        return;
    }
    if (!self.locService) {
        self.locService = [[LocationGetObj alloc] init];
    }
    self.locService.delegate = self;
    [self.locService startLocation];
}
- (void)getLocationSuccess:(BMKUserLocation *)userLocation{
    _location = userLocation.location.coordinate;
    if([self.dic_type isEqualToString:@"meishi"]){
        [self baiduMeishiSearch];
    }else{
        [self netRequest:_location andRresh:NO];
    }
    BMKReverseGeoCodeOption *geo = [[BMKReverseGeoCodeOption alloc] init];
    geo.reverseGeoPoint = _location;
    self.locService.geoDelegate = self;
    BOOL ret = [self.locService startReverseGeoCode:geo];
    if (!ret) {
        [self.locService startReverseGeoCode:geo];
    }
    [self.locService stopLocation];
}

//TODO:百度poi搜索
- (void)baiduMeishiSearch {
    //初始化检索对象
    _search =[[BMKPoiSearch alloc]init];
    _search.delegate = self;
    //发起检索
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    option.pageIndex = _currenPage;
    option.pageCapacity = 10;
    option.location = _location;
    option.keyword = @"小吃";
    BOOL flag = [_search poiSearchNearBy:option];
     if(flag)
    {
        NSLog(@"周边检索发送成功");
    }
    else
    {
        NSLog(@"周边检索发送失败");
    }
}

- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        _countPage = poiResult.pageNum;
        _currenPage = poiResult.pageIndex;
        _tableDataSource = [NSMutableArray arrayWithArray:poiResult.poiInfoList];

    }
    else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    } else {
        NSLog(@"抱歉，未找到结果");
    }
}

/**
 *返回POI详情搜索结果
 *@param searcher 搜索对象
 *@param poiDetailResult 详情搜索结果
 *@param errorCode 错误号，@see BMKSearchErrorCode
 */
- (void)onGetPoiDetailResult:(BMKPoiSearch*)searcher result:(BMKPoiDetailResult*)poiDetailResult errorCode:(BMKSearchErrorCode)errorCode{
    
}

- (void)onGetReverseGeoCodeResultSuccess:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
  
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setObject:result.addressDetail.district forKey:@"district"];
    [dic setObject:result.addressDetail.city forKey:@"city"];
    [dic setObject:result.addressDetail.province forKey:@"province"];
    NSDictionary *location = @{@"lat":@(result.location.latitude),@"lon":@(result.location.longitude)};
    [dic setObject:location forKeyedSubscript:@"location"];
    [Common setCurrenCity:dic];
    if(_rightBtn.titleLabel.text.length > 0) {
        return;
    }
    [self setRightBtnTitle]; }


- (void)onGetGeoCodeResultSuccess:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if(_rightBtn.titleLabel.text.length > 0) {
        return;
    }
    [self setRightBtnTitle];}

- (void)setRightBtnTitle {
    NSDictionary *dic = [Common currenCity];
    if (!dic) {
        [_rightBtn setTitle:[dic customObjectForkey:@"定位失败"] forState:UIControlStateNormal];
        return;
    }
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setFrame:CGRectMake(15, 5.0f, 60, 30)];
    [_rightBtn setTitle:[dic customObjectForkey:@"city"] forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(changeVcShowView:) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
}


- (void)initAbout{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[@"保养",@"洗车",@"维修",@"美食"] forKeys:@[@"upkeep",@"jzxc",@"weixiu",@"meishi"]];
    self.title = [dic objectForKey:self.dic_type];
    [self.tableView addFooterWithTarget:self action:@selector(footerRresh)];
    REGISTCELL(@"DrawTrailerTableViewCell", cell);
    self.tableView.tableFooterView = [UIView new];
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:@selector(navigationLeftBtnAction) andCustom:NO];
   
}



- (void)netReqestForCityId:(NSString *)cityId {
    if (!self.carAround) {
        self.carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    if (_tableDataSource) {
        [_tableDataSource removeAllObjects];
        _tableDataSource = nil;
    }
    _currenPage = 1;
    _countPage = 0;
    _cityId = [cityId copy];
    self.carAround.lat = [NSString stringWithFormat:@"%f",_location.latitude];
    self.carAround.lon = [NSString stringWithFormat:@"%f",_location.longitude];
    self.carAround.dic_type = self.dic_type;
    self.carAround.cityId = _cityId;
    
    self.carAround.page = [NSString stringWithFormat:@"%ld",_currenPage];
    [self.carAround carAroundInfoWithCityId:^(id result) {
        _tableDataSource = [NSMutableArray arrayWithArray:[result objectForKey:@"sellerlist"]];
        _countPage = [[result objectForKey:@"totalpages"] integerValue];
        if (!self.tableView.delegate) {
            self.tableView.delegate = self;
            self.tableView.dataSource  =  self;
        }
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }anfFail:^(id result) {
        _currenPage --;
    }];
}

- (void)navigationLeftBtnAction{
    if (_isCarCategory) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

//TODO:跳转地址选择
- (void)changeVcShowView:(UIButton *)btn{
    RegionSeletedViewController *selete = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"regionSeleted"];
    selete.target = self;
    
    selete.action = @selector(regionSeleteAction:);
    [self.navigationController pushViewController:selete animated:YES];
}

#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableDataSource.count <= 0 ? 0 : _tableDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_dic_type isEqualToString:@"meishi"]) {
        return nil;
    }else {
        DrawTrailerTableViewCell *drawCell = [tableView dequeueReusableCellWithIdentifier:cell forIndexPath:indexPath];
        drawCell.superType = @"carAround";
        drawCell.selectionStyle = UITableViewCellSelectionStyleNone;
         drawCell.info = [_tableDataSource objectAtIndex:indexPath.row];
        [drawCell.praiseView removeGestureRecognizer:drawCell.tap];
        return drawCell;
    }
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CarServiceDetailViewController *service = [[CarServiceDetailViewController alloc] initWithNibName:@"CarServiceDetailViewController" bundle:nil];
    service.dic_type = _dic_type;
    service.distance = [[_tableDataSource objectAtIndex:indexPath.row] customObjectForkey:@"SFZ"];
    service.shopId = [[_tableDataSource objectAtIndex:indexPath.row] objectForKey:@"ID"];
    [self.navigationController pushViewController:service animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 88;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
